import Taro, {Component} from '@tarojs/taro'
import {View, Image, Text, ScrollView} from '@tarojs/components'
import {observer, inject} from '@tarojs/mobx'
import {formatNumber, getAvatar, getUserInfo, pageSize, showToast, subTime} from '../../utils/common'
import {UserProfitOutput, CommOutput} from '../../api/api'

import './profit.scss'
import profitBg from '../../assets/img/bg_03.jpg'
import nav_01 from "../../assets/img/banner_01.jpg";
import FooterMenu from "../../components/FooterMenu";


import {IStoreProps} from '../../store/Stores'

interface IHomeProps extends IStoreProps {
}

@inject("stores")
@observer
class MineProfit extends Component<IHomeProps> {
  state = {
    pageIndex: 1,
    pageSize: pageSize,
    items: [] as CommOutput[],
    totalCount: 0,
    navs: [
      {id: 1, title: '养鱼收益'},
      {id: 2, title: '其他收益'}
    ],
    currentNavId: 1,
    userProfit: {} as UserProfitOutput
  }

  componentDidMount(): void {
    let userInfo = getUserInfo() || {}
    let pagesArr = Taro.getApp().state.pagesArr || []
    let hashUrl = window.location.hash
    pagesArr.map(item => {
      if('#/'  + item.path === hashUrl ) {
        if(item.isLogin && Object.keys(userInfo).length <= 0) {
          Taro.navigateTo({ url: '/pages/index/index' });
        } else if (item.isLogin && !userInfo.userPhone) {
          Taro.navigateTo({ url: '/pages/login/login' });
        }
      }
    })
    this.userProfitAsync()
    this.getItems()
  }

  link = (url: string) => {
    let { userProfit } = this.state
    if(url === '/pages/mine/cash' && userProfit.account && userProfit.account < 100) {
      showToast('收益小于100元, 不能提现哦~'); return
    }else {
      Taro.navigateTo({url})
    }
  }

  userProfitAsync() {
    let {userStore} = this.props.stores
    userStore.userProfitAsync({
      callback: res => {
        this.setState({userProfit: res})
      }
    })
  }

  getItems = () => {
    let { userStore } = this.props.stores
    let { pageIndex, pageSize, currentNavId } = this.state
    userStore.incomeRecord({
      commType: currentNavId,
      pageIndex,
      pageSize,
      callback: res => {
        if (this.state.pageIndex === 1) {
          this.setState({totalCount: res.totalCount, items: res.items})
        }else {
          const { items } = this.state;
          items.push(...res.items || []);
          this.setState({totalCount: res.totalCount, items})
        }
      }
    })
  }

  onReachBottom(): void {
    let {totalCount, pageSize, pageIndex} = this.state
    const {loading} = this.props.stores.homeStore;
    if (totalCount > pageIndex * pageSize && !loading) {
      this.setState({
        pageIndex: pageIndex + 1
      }, () => {
        this.getItems()
      })
    }
  }

  setCurrentNavId(id: number) {
    this.setState({ currentNavId: id, items: [], pageIndex: 1 }, () => { this.getItems() })
  }

  render() {
    let {items, navs, userProfit, currentNavId} = this.state
    return (
      <View className='mine-profit page-bg'>
        <View className='mine-profit__header'>
          <Image className='mine-profit__bg' src={profitBg}/>
          <View className='line '>
            <Text className='tip'>可提现收益(元)</Text>
            <View className='log icon-link' onClick={this.link.bind(this, '/pages/mine/cashRecord')}>提现记录</View>
          </View>
          <View className='line'>
            <View className='money'>{(userProfit.account || 0).toFixed(2)}</View>
            <View className='cash-btn icon-link-theme' onClick={this.link.bind(this, '/pages/mine/cash')}>立即提现</View>
          </View>
          <View className='line line-item'>
            <View className='item'>
              <Text className='item-tip'>今日收益(元)</Text>
              <Text className='item-money'>{(userProfit.terdayProfit || 0).toFixed(2)}</Text>
            </View>
            <View className='item'>
              <Text className='item-tip'>昨日收益(元)</Text>
              <Text className='item-money'>{(userProfit.yesterdayProfit || 0).toFixed(2)}</Text>
            </View>
            <View className='item'>
              <Text className='item-tip'>累计收益(元)</Text>
              <Text className='item-money'>{(userProfit.cumProfit || 0).toFixed(2)}</Text>
            </View>
          </View>
        </View>

        <ScrollView className='scroll-view-nav' scrollX>
          {
            navs.map(item => {
              return (
                <View className={currentNavId === item.id ? 'scroll-item scroll-item-on' : 'scroll-item'}
                      style={{width: '50%'}} key={item.id}
                      onClick={this.setCurrentNavId.bind(this, item.id)}
                >{item.title}<Text className='line' /></View>
              )
            })
          }
        </ScrollView>

        <View className='mine-profit__main'>
          {
            items.length <= 0 &&
            <View className='none'>
                <Image className='none__icon' src={require('../../assets/img/common/none.png')}/>
                <View className='none__desc desc'>暂时还没有任何收益记录！</View>
            </View>
          }
          {
            (items.length > 0 && currentNavId ===1) &&
            <View className='list03'>
              {
                items.map(item => {
                  return(
                    <View className='list01__item'>
                      <Image className='list01__img' src={item.avatar} />
                      <View className='list01__info'>
                        <View className='list01__line'>
                          <View className='list01__date'>第{formatNumber(item.periodsNum)}期</View>
                          <View className='list01__title'>{item.comName}</View>
                          <View className='list01__status'>+{item.commission}</View>
                        </View>
                        <View className='list01__line'>
                          <View className='desc'>{subTime(item.creationTime)}</View>
                        </View>
                        <View className='list01__line list01__line-i'>
                        {/*   <View className='list01__i'>
                            收益({(item.proportion || 0) *100}%)
                          </View>
                          <View className='list01__i'>
                            期限({item.cultureDays}天)
                          </View> */}
                          <View className='list01__i'>
                            数量({item.productQuantity}条)
                          </View>
                        </View>
                      </View>
                    </View>
                  )
                })
              }
            </View>
          }
            
          {
            (items.length > 0 && currentNavId === 2) &&
            <View className='list-04 content-20'>
              {
                items.map(item => {
                  return(
                    <View className='list-04__item content-20' key={item.id}>
                      <Image className='list-04__avatar' src={getAvatar(item.avatar || '')} />
                      <View className='list-04__info'>
                        <View className='list-04__title'>{item.comName} {item.explain}</View>
                        <View className='list-04__date font-dark'>{subTime(item.creationTime)}</View>
                      </View>
                      <View className='list-04__profit color-orange price'>+{item.commission}</View>
                    </View>
                    )
                })
              }
            </View>
          }

        </View>

        <View className='footer-block'/>
        <FooterMenu menu='profit' />

      </View>
    )
  }
}

export default MineProfit
